package com.yanq.liancar.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.SelectVipAdapter;
import com.yanq.liancar.adapter.SmallBPayAdapter;
import com.yanq.liancar.bean.PayNowBean;
import com.yanq.liancar.bean.PayResult;
import com.yanq.liancar.bean.SelectVipVarietyBean;
import com.yanq.liancar.bean.ServiceAliPayBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.WeChatPayBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;
import com.yanq.liancar.view.RecyclerViewSpacesItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.internal.schedulers.NewThreadWorker;

public class SmallCBuyVIPPayActivity extends BaseToolbarActivity {

    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.pay_recycleview)
    RecyclerView payRecycleview;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.tv_CustomerService)
    TextView tv_CustomerService;
    @BindView(R.id.gridview_vip)
    RecyclerView gridview_vip;
    private List<PayNowBean> payNowBeanList = new ArrayList<>();
    private List<SelectVipVarietyBean.DataBean> mVarietyList = new ArrayList<>();
    private SelectVipAdapter mSelectVipAdapter;
    private SmallBPayAdapter adapter;
    private int payType=1;
    private double price;
    private int vipvarietyid;
    private IWXAPI api;
    private static final String APP_ID = "wxd2e19fc6b6f17ec0";
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**

                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。

                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtils.e("resultInfo====", resultInfo);
                    LogUtils.e("resultStatus====", resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        RxToast.success("下单成功");
                        finish();
                    } else {

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        RxToast.error("支付失败");
                    }
                    break;
                }

            }

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small_cbuy_vippay);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("购买VIP");
        initData();
        initRecyclerView();
//

        SpannableString spannableString = new SpannableString("遇到支付问题请联系客服");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.main_color));
        spannableString.setSpan(colorSpan, 7, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan3 = new ForegroundColorSpan(getResources().getColor(R.color.background_content));
        spannableString.setSpan(colorSpan3, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv_CustomerService.setText(spannableString);

        getVipVariety();
    }

    private void initData() {
        PayNowBean bean = new PayNowBean();
        bean.setNum(1);
        bean.setName("支付宝支付");
        bean.setChecked(true);
        payNowBeanList.add(bean);
        PayNowBean bean2 = new PayNowBean();
        bean2.setNum(2);
        bean2.setName("微信支付");
        bean2.setChecked(false);
        payNowBeanList.add(bean2);
    }

    private void initRecyclerView() {
        gridview_vip.setNestedScrollingEnabled(false);
        gridview_vip.setLayoutManager(new GridLayoutManager(this, 2));
        mSelectVipAdapter = new SelectVipAdapter(R.layout.item_small_selectvip, mVarietyList);
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.LEFT_DECORATION,50);//左间距
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.RIGHT_DECORATION,50);//右间距
        gridview_vip.addItemDecoration(new RecyclerViewSpacesItemDecoration(stringIntegerHashMap));
        gridview_vip.setAdapter(mSelectVipAdapter);
        mSelectVipAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i <mVarietyList.size() ; i++) {
                    if (i==position){
                        mVarietyList.get(position).setCkecked(true);
                    }else {
                        mVarietyList.get(i).setCkecked(false);
                    }
                }
                price=mVarietyList.get(position).getVipvariety_price();
                vipvarietyid=mVarietyList.get(position).getVipvariety_id();
                mSelectVipAdapter.notifyDataSetChanged();
            }
        });

        payRecycleview.setNestedScrollingEnabled(false);
        payRecycleview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SmallBPayAdapter(R.layout.item_small_b_pay, payNowBeanList);
        payRecycleview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < payNowBeanList.size(); i++) {
                    if (position == i) {
                        payNowBeanList.get(i).setChecked(true);
                        payNowBeanList.get(i).getName();
                        payType=payNowBeanList.get(position).getNum();
                    } else {
                        payNowBeanList.get(i).setChecked(false);
                    }
                }
                adapter.setNewData(payNowBeanList);
            }
        });
    }

    @OnClick({ R.id.tv_pay,R.id.tv_CustomerService})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            case R.id.ll_ordinary:
//                llOrdinary.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
//                tvPrice.setTextColor(Color.WHITE);
//                tvYuan.setTextColor(Color.WHITE);
//
//                llSuper.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
//                tvPrice1.setTextColor(getResources().getColor(R.color.main_color));
//                tvYuan1.setTextColor(getResources().getColor(R.color.main_color));
//                price=600;
//                vipvarietyid=1;
//                break;
//            case R.id.ll_super:
//                llOrdinary.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_a));
//                tvPrice.setTextColor(getResources().getColor(R.color.main_color));
//                tvYuan.setTextColor(getResources().getColor(R.color.main_color));
//
//                llSuper.setBackground(getResources().getDrawable(R.drawable.selector_tv_bg_b));
//                tvPrice1.setTextColor(Color.WHITE);
//                tvYuan1.setTextColor(Color.WHITE);
//                price=900;
//                vipvarietyid=2;
//                break;
            case R.id.tv_pay:
                if (vipvarietyid!=0){
                    if (payType==1){
                        aLiPay();
                    }else {
                        weChatPay();
                    }
                }else {
                    RxToast.info("请选择会员类型");
                }

                break;
            case R.id.tv_CustomerService:
//                String title = "智能客服";
//                ConsultSource source = new ConsultSource("", "我的", "custom information string");
//                Unicorn.openServiceActivity(this, title, source);
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4008055011"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
        }
    }

    private void getVipVariety(){
        OkGo.<String>post(Config.s + "llc/api/selectVipVariety")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SelectVipVarietyBean bean=gson.fromJson(response.body(),SelectVipVarietyBean.class);
                        if (bean.isIsSuccess()){
                            mVarietyList.clear();
                            mVarietyList.addAll(bean.getData());
                            mSelectVipAdapter.setNewData(mVarietyList);
                        }
                    }
                });
    }

    //支付宝支付
    private void aLiPay() {
        OkGo.<String>post(Config.s + "llc/api/AlipayBuyVip")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("vippayment", payType)
                .params("vipamount", price)
                .params("vipvarietyid", vipvarietyid)
                .params("orderType", 5)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        final ServiceAliPayBean baseBean=gson.fromJson(response.body(),ServiceAliPayBean.class);
                        if (baseBean.isIsSuccess()){
                            if (baseBean.getCode()==200){
                                final String info= baseBean.getData().getSigned_content();
                                LogUtils.e("加签info===",info);
                                if ("".equals(info)||!TextUtils.isEmpty(info)){
                                    Runnable payRunnable = new Runnable() {
                                        @Override
                                        public void run() {
                                            PayTask alipay = new PayTask(SmallCBuyVIPPayActivity.this);
                                            Map<String, String> result = alipay.payV2(info, true);

                                            Message msg = new Message();
                                            msg.what = SDK_PAY_FLAG;
                                            msg.obj = result;
                                            mHandler.sendMessage(msg);
                                            LogUtils.e("13123131",baseBean.getData().getOnum()+"");
                                        }
                                    };
                                    // 必须异步调用
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                }
                            }else {
                                RxToast.info(baseBean.getOutputMessage());
                            }

                        }else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }
                });
    }

    //微信支付
    private void weChatPay() {
        api = WXAPIFactory.createWXAPI(this,APP_ID);
        api.registerApp(APP_ID);
        OkGo.<String>post(Config.s + "llc/api/WXBuyVip")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .params("vippayment", payType)
                .params("vipamount", price)
                .params("vipvarietyid", vipvarietyid)
                .params("orderType", 5)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WeChatPayBean baseBean=gson.fromJson(response.body(),WeChatPayBean.class);
                        if (baseBean.isIsSuccess()){
                            PayReq request = new PayReq();
                            request.appId = baseBean.getData().getAppid();
                            request.partnerId =baseBean.getData().getPartnerId();
                            request.prepayId= baseBean.getData().getPrepayId();
                            request.packageValue = baseBean.getData().getPackageValue();
                            request.nonceStr= baseBean.getData().getNonceStr();
                            request.timeStamp= baseBean.getData().getTimeStamp();
                            request.sign= baseBean.getData().getSign();
                            api.sendReq(request);
                            LogUtils.e(" api.sendReq=====",api.sendReq(request)+"");
                        }else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }


                });
    }
}
